<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="订单编号" prop="orderSn">
          <el-input
            v-model="queryParams.orderSn"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option
              v-for="dict in orderStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="order-card" v-loading="loading">
      <div v-for="order in orderList" :key="order.id" class="order-item">
        <div class="order-header">
          <div class="order-info">
            <span class="order-sn">订单编号：{{ order.orderSn }}</span>
            <span class="order-time">下单时间：{{ formatTime(order.createTime) }}</span>
          </div>
          <div class="order-status">
            <el-tag :type="getOrderStatusType(order.status)">
              {{ getOrderStatusLabel(order.status) }}
            </el-tag>
          </div>
        </div>

        <div class="order-content">
          <div class="product-list">
            <div v-for="item in order.items" :key="item.id" class="product-item">
              <div class="product-image-container">
                <el-image 
                  :src="getImageUrl(item.pic)"
                  :alt="item.productName"
                  class="product-image"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon :size="30"><picture-filled /></el-icon>
                      <span>暂无图片</span>
                    </div>
                  </template>
                  <template #placeholder>
                    <div class="image-loading">
                      <el-icon :size="30" class="is-loading"><loading /></el-icon>
                      <span>加载中...</span>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="product-info">
                <div class="product-name" :title="item.productName">{{ item.productName }}</div>
                <div class="product-attrs" v-if="item.spData">{{ item.spData }}</div>
                <div class="product-price">
                  <span class="price">￥{{ formatPrice(item.salePrice) }}</span>
                  <span class="quantity">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="order-footer">
          <div class="order-summary">
            <span class="order-count">共 {{ getOrderItemCount(order) }} 件商品</span>
            <span class="order-amount">
              实付金额：<span class="amount">￥{{ formatPrice(order.payAmount) }}</span>
            </span>
          </div>
          <div class="order-actions">
            <template v-if="order.status === 0">
              <!-- 待付款 -->
              <el-button type="primary" size="small" @click="handlePay(order)">立即付款</el-button>
              <el-button size="small" @click="handleCancel(order)">取消订单</el-button>
            </template>
            <template v-else-if="order.status === 2">
              <!-- 待收货 -->
              <el-button type="success" size="small" @click="handleConfirmReceive(order)">确认收货</el-button>
              <el-button size="small" @click="handleViewLogistics(order)">查看物流</el-button>
            </template>
            <template v-else-if="order.status === 3">
              <!-- 已完成 -->
              <el-button size="small" @click="handleDelete(order)">删除订单</el-button>
            </template>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-if="total > 0"
          v-model="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { PictureFilled, Loading } from '@element-plus/icons-vue'
import { 
  listOrder,
  payOrder,
  cancelOrder,
  confirmReceiveOrder,
  deleteOrder,
  getOrderLogistics
} from '@/api/order'
import { useRouter } from 'vue-router'

const router = useRouter()

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderSn: undefined,
  status: undefined
})

// 订单状态选项
const orderStatusOptions = [
  { value: 0, label: '待付款' },
  { value: 1, label: '待发货' },
  { value: 2, label: '已发货' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已关闭' },
  { value: 5, label: '无效订单' }
]

// 数据
const loading = ref(false)
const total = ref(0)
const orderList = ref([])

// 获取订单列表
const getList = async () => {
  try {
    loading.value = true
    const response = await listOrder(queryParams.value)
    orderList.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderSn: undefined,
    status: undefined
  }
  getList()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 获取订单状态标签
const getOrderStatusLabel = (status) => {
  const option = orderStatusOptions.find(item => item.value === status)
  return option ? option.label : '未知状态'
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待付款
    case 1: return 'primary'  // 待发货
    case 2: return 'success'  // 待收货
    case 3: return ''         // 已完成
    case 4: return 'info'     // 已取消
    default: return 'info'
  }
}

// 订单操作
// const handlePay = (order) => {
//   router.push({
//     path: `/order/pay/${order.orderSn}`
//   })
// }

const handlePay = (order) => {
  router.push({
    path: `/order/pay/${order.orderSn}`
  })
}

const handleCancel = (order) => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await cancelOrder(order.orderSn)
      ElMessage.success('订单已取消')
      getList()
    } catch (error) {
      ElMessage.error('取消订单失败')
    }
  })
}

const handleConfirmReceive = (order) => {
  ElMessageBox.confirm('确认已收到商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await confirmReceiveOrder(order.id)
      ElMessage.success('确认收货成功')
      getList()
    } catch (error) {
      ElMessage.error('确认收货失败')
    }
  })
}

const handleViewLogistics = (order) => {
  // TODO: 实现查看物流功能
  ElMessage.info('物流信息查看功能开发中')
}

const handleDelete = (order) => {
  ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteOrder(order.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 格式化图片URL
const getImageUrl = (pic) => {
  if (!pic) return ''
  if (pic.startsWith('http')) {
    return pic
  }
  return import.meta.env.VITE_APP_BASE_API + pic
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取订单商品总数
const getOrderItemCount = (order) => {
  if (!order.items) return 0
  return order.items.reduce((total, item) => total + (item.quantity || 0), 0)
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .order-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    :deep(.el-card__body) {
      padding: 20px;
    }

    .order-item {
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 20px;
      overflow: hidden;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
      }

      .order-header {
        background-color: #f8f9fb;
        padding: 16px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #e4e7ed;

        .order-info {
          .order-sn {
            margin-right: 20px;
            color: #303133;
            font-weight: 500;
            font-size: 15px;
          }

          .order-time {
            color: #909399;
            font-size: 13px;
          }
        }

        .order-status {
          :deep(.el-tag) {
            padding: 0 12px;
            height: 28px;
            line-height: 26px;
            font-size: 13px;
            border-radius: 4px;
          }
        }
      }

      .order-content {
        padding: 20px;
        background: #fff;

        .product-list {
          .product-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #f0f0f0;

            &:last-child {
              border-bottom: none;
            }

            .product-image-container {
              width: 100px;
              height: 100px;
              margin-right: 20px;
              border-radius: 8px;
              overflow: hidden;
              border: 1px solid #ebeef5;
              background: #fff;

              .product-image {
                width: 100%;
                height: 100%;
                transition: transform 0.3s ease;
                object-fit: cover;

                &:hover {
                  transform: scale(1.05);
                }
              }

              .image-placeholder,
              .image-loading {
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                background-color: #f8f9fb;
                color: #909399;

                .el-icon {
                  margin-bottom: 8px;
                  font-size: 24px;
                }

                span {
                  font-size: 12px;
                }
              }
            }

            .product-info {
              flex: 1;
              min-width: 0;
              padding-right: 20px;

              .product-name {
                font-size: 15px;
                color: #303133;
                margin-bottom: 10px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-weight: 500;

                &:hover {
                  color: var(--el-color-primary);
                }
              }

              .product-attrs {
                font-size: 13px;
                color: #909399;
                margin-bottom: 10px;
                line-height: 1.4;
              }

              .product-price {
                display: flex;
                align-items: baseline;
                justify-content: space-between;

                .price {
                  color: #f56c6c;
                  font-size: 16px;
                  font-weight: bold;
                }

                .quantity {
                  color: #909399;
                  font-size: 14px;
                }
              }
            }
          }
        }
      }

      .order-footer {
        padding: 16px 20px;
        background-color: #f8f9fb;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #e4e7ed;

        .order-summary {
          .order-count {
            color: #606266;
            margin-right: 20px;
            font-size: 14px;
          }

          .order-amount {
            color: #606266;
            font-size: 14px;

            .amount {
              color: #f56c6c;
              font-size: 20px;
              font-weight: bold;
              margin-left: 5px;
            }
          }
        }

        .order-actions {
          display: flex;
          gap: 10px;

          .el-button {
            padding: 8px 16px;
            font-size: 13px;
            border-radius: 4px;
            
            &--primary {
              background: var(--el-color-primary);
              border-color: var(--el-color-primary);
              
              &:hover {
                background: var(--el-color-primary-light-3);
                border-color: var(--el-color-primary-light-3);
              }
            }
            
            &--success {
              background: var(--el-color-success);
              border-color: var(--el-color-success);
              
              &:hover {
                background: var(--el-color-success-light-3);
                border-color: var(--el-color-success-light-3);
              }
            }
          }
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    padding: 10px 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: flex-end;
  }
}

// 添加响应式样式
@media screen and (max-width: 768px) {
  .app-container {
    padding: 10px;

    .order-item {
      .order-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }

      .product-item {
        flex-direction: column;
        align-items: flex-start;

        .product-image-container {
          margin-right: 0;
          margin-bottom: 15px;
        }

        .product-info {
          width: 100%;
          padding-right: 0;
        }
      }

      .order-footer {
        flex-direction: column;
        gap: 15px;

        .order-summary {
          width: 100%;
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .order-actions {
          width: 100%;
          justify-content: flex-end;
        }
      }
    }
  }
}
</style> 